// pages/patrol/patrol.js
var util = require("../../utils/util.js")
var api = require("../../utils/api.js")
var QQMapWX = require('../../utils/qqmap/qqmap-wx-jssdk.js');
const uploadImage = require('../../utils/oss/uploadAliyun.js');
var qqmapsdk;
var a = false
let app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        length: 0,
        whether: 0,
        text: '大家一起来巡河啊',
        record: 1,
       
        tinct: [],
        tinctid: 0,
        rubbish: [],
        rubbishid: 0,
        flowing: [],
        flowingid: 0,
        selectbe: [],
        problemlist: [],
        problemlist_id: -1,
        problemlist_num: [],
        select_id: -1,
        select_num: [],
        problem_num: [],
        backtrackid: 0,
        province: '',
        city: '',
        district: '',
        address: '',
        photos: [],
        showphotos: [],
        touch_start: 0,
        touch_end: 0,
        longitude: '',
        latitude: '',
        account_id: 0,
        rpid: 0,
        pid: 0,
        nvabarData: {
            showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
            title: '新增标记', //导航栏 中间的标题
        },
        height: app.globalData.height * 2 + 20,
        flag: 0,
        startext: [],
        stardata: [1, 2, 3, 4, 5],
        placeholder: '请描述改位置的河流状况，如水的颜色、气味,标志性建筑，或其他想分享的美好景观等',
    },
    //多项选择
    select: function(e) {

        var that = this
            // if (that.data.problem_num.length) {
            //     api.showError("已选择问题标签")
            //     return
            // }
        var index = e.currentTarget.dataset.index;
        var select_num = that.data.select_num;
        if (that.data.selectbe[index].class == 'view-garbage1') {
            that.data.selectbe[index].class = 'view-garbage2'
            select_num.push(e.currentTarget.dataset.id)
        } else {
            that.data.selectbe[index].class = 'view-garbage1'
            util.removeByValue(select_num, e.currentTarget.dataset.id)
        }
        that.setData({
            selectbe: that.data.selectbe,
            select_num: select_num
        })
    },
    onChangeAddress: function() {
        a = true
        let vm = this;
        wx.chooseLocation({
            success: function(address) {
                // success
                qqmapsdk.reverseGeocoder({
                    location: {
                        latitude: address.latitude,
                        longitude: address.longitude
                    },
                    success: function(res) {
                        vm.setData({
                            province: res.result.address_component.province,
                            city: res.result.address_component.city,
                            district: res.result.address_component.district,
                            address: res.result.address_component.street_number,
                            longitude: address.longitude,
                            latitude: address.latitude,
                        })
                    }
                });
            },
            fail: function() {
                // fail
            },
            complete: function() {
                // complete
            }
        })
    },
    //多项选择
    problem: function(e) {
        var that = this
            // if (that.data.select_num.length) {
            //     api.showError("已选择美好标签")
            //     return
            // }
        var index = e.currentTarget.dataset.index;
        var problem_num = that.data.problem_num;
        if (that.data.problemlist[index].class == 'view-garbage1') {
            that.data.problemlist[index].class = 'view-garbage3'
            problem_num.push(e.currentTarget.dataset.id)
        } else {
            that.data.problemlist[index].class = 'view-garbage1'
            util.removeByValue(problem_num, e.currentTarget.dataset.id)
        }
        that.setData({
            problemlist: that.data.problemlist,
            problem_num: problem_num
        })
    },
   
    article: function(e) {
        wx.navigateTo({
            url: '../article/article?id=' + e.currentTarget.id,
        })
    },
    
    //获取输入的字数
    userInput: function(e) {
        var that = this
        if (e.detail.value == '') {
            that.setData({
                length: e.detail.value.length,
            })

        } else {
            that.setData({
                length: e.detail.value.length,
                text: e.detail.value
            })
        }

    },
    //判断是还是否
    isalpha: function(e) {
        var that = this
        if (that.data.whether == 0) {
            that.setData({
                whether: e.currentTarget.dataset.id
            })
        } else {
            that.setData({
                whether: 0
            })
        }
    },
    //更多
    evenmore: function() {
        var that = this
        that.setData({
            record: 2
        })
    },
    //举报
    report: function(e) {
        var that = this
        that.setData({
            backtrackid: 1,
        })
    },
    //暂不举报
    cancel: function() {
        this.setData({
            backtrackid: 0
        })
    },
    //立马举报
    immediately: function() {
        wx.makePhoneCall({
            phoneNumber: '12345',
        })
    },
    backtrack: function() {
        this.setData({
            backtrackid: 0
        })
    },
    onLoad: function(options) {
        let that = this
        if (options.rpid) {
            that.setData({
                rpid: options.rpid
            })
        } else {
            that.setData({
                rpid: 0
            })
        }
        if (options.pid) {
            that.setData({
                pid: options.pid
            })
        } else {
            that.setData({
                pid: 0
            })
        }
    },
    gettags: function(e) {
        var that=this
        let data = {}
        let url = app.u.H + app.u.river.GETTAGS
        api.requestUrl(data, url).then(res => {
          console.log(res.data)
          that.setData({
                // smell: res.data.smell,
                // tinct: res.data.color,
                // rubbish: res.data.rubbish,
                // flowing: res.data.flowing,
                selectbe: res.data.good,
                problemlist: res.data.worse
            })
        })
    },
    changeColor: function(e) {
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.no;
        var b = 'startext[' + index + ']';
        var that = this;
        if (num == 1) {
            that.setData({
                flag: 1,
                [b]: '各方面都很差'
            });
        } else if (num == 2) {
            that.setData({
                flag: 2,
                [b]: '比较差'
            });
        } else if (num == 3) {
            that.setData({
                flag: 3,
                [b]: '还需改善'
            });
        } else if (num == 4) {
            that.setData({
                flag: 4,
                [b]: '比较满意，仍可改善'
            });
        } else if (num == 5) {
            that.setData({
                flag: 5,
                [b]: '非常满意，无可挑剔'
            });
        }
    },
    /**
     * 防止穿透
     */
    doNotMove: function() {
        return;
    },
    getLocal: function(latitude, longitude) {

        let vm = this;
        if (vm.data.rpid == 0 && vm.data.pid == 0) {
            wx.getStorage({
                key: 'river_id',
                success: function(res) {
                    vm.setData({
                        rpid: res.data
                    })
                }
            })
        }
        wx.getStorage({
            key: 'userinfo',
            success: function(res) {
                // success
                vm.setData({
                    account_id: res.data.id
                })
            },

        })
        qqmapsdk.reverseGeocoder({
            location: {
                latitude: latitude,
                longitude: longitude
            },
            success: function(res) {
                console.log(res)
                vm.setData({
                    province: res.result.address_component.province,
                    city: res.result.address_component.city,
                    district: res.result.address_component.district,
                    address: res.result.address_component.street_number,
                    longitude: longitude,
                    latitude: latitude,

                })
            }
        });
    },
    mytouchstart: function(e) {
        this.setData({
            touch_start: e.timeStamp
        })
    },
    mytouchend: function(e) {
        this.setData({
            touch_end: e.timeStamp
        })
    },
    addimg: function() {
        a = true
            // api.chooseimage(9, this.data.photos, 'file', app.u.H + app.u.me.UPLOADIMG).then(res => {
            //     console.log(res)
            //     this.setData({
            //         photos: this.data.photos.concat(res)
            //     })
            // })
        let that = this
        wx.chooseImage({
            sizeType: 'original,compressed',
            sourceType: ['album', 'camera'],
            success: function(res) {
                if ((that.data.showphotos.length + res.tempFilePaths.length) > 9) {
                    api.showError('最多上传9张图')
                    return
                } else {
                    that.setData({
                        showphotos: that.data.showphotos.concat(res.tempFilePaths)
                    })
                    let data = new Date();
                    Promise.all(res.tempFilePaths.map((fileurl) => {
                        //var oss = "http://riverwatcher-bucket.oss-cn-shenzhen.aliyuncs.com/";
                        // let url = util.formatDataYMD(data) + "/" + util.sha1(fileurl) + '.jpg'
                        let url = util.formatDataYMD(data) + "/" + fileurl.replace('wxfile://', '')

                        that.setData({
                            photos: that.data.photos.concat(app.globalData.ossUrl + url)
                        })
                        console.log("url----------", url, "fileurl---", fileurl);
                        //filePath为要上传的本地文件的路径
                        //第二个参数为oss目录
                        uploadImage(fileurl, util.formatDataYMD(data) + "/",
                            function(res) {
                                console.log("上传成功")
                                    //todo 做任何你想做的事
                            },
                            function(res) {
                                console.log("上传失败")
                                    //todo 做任何你想做的事
                            }
                        )

                        // wx.uploadFile({
                        //     url: app.u.H + app.u.me.OSUPLOADIMG,
                        //     // url: 'http://river.cc/api/me/osuploadimg',
                        //     filePath: fileurl,
                        //     name: 'file',
                        //     formData: {
                        //         'type': 'file',
                        //         'name': url,
                        //     },
                        //     success: function(res) {
                        //         if (res.statusCode === 200) {}
                        //     }

                        // })
                    }))
                }

            }
        })
    },

    delimg: function(e) {
        let that = this
        let images = that.data.photos
        let images2 = that.data.showphotos
        var index = e.currentTarget.dataset.index
        wx.showModal({
            title: '提示',
            content: '确定要删除此图片吗？',
            success(res) {
                if (res.confirm) {
                    images.splice(index, 1)
                    images2.splice(index, 1)
                    that.setData({
                        photos: images,
                        showphotos: images2
                    })
                } else if (res.cancel) {}
            }
        })
    },
    viewimg: function(e) {
        wx.previewImage({
            current: e.currentTarget.dataset.url,
            urls: this.data.showphotos
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        if (a) {
            a = false;
            return;
        }
        let that = this
        qqmapsdk = new QQMapWX({
            key: 'TTWBZ-6L56U-W55V3-BJZJ6-KGGYF-O2BRB' // 必填
        });
        wx.getLocation({
            type: 'gcj02', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
            success: function(res) {
                // success
                that.getLocal(res.latitude, res.longitude)
                that.gettags()
            }
        })

    },
    confirm: function(e) {
        
        let that = this
            // if (that.data.text === '') {
            //     api.showError('描述不能为空')
            //     return
            // }
        if (that.data.photos[0] === '') {
            api.showError('图片不能为空')
            return
        }
        if (that.data.province === '') {
            api.showError('地址自动获取失败，请重新选择定位')
            return
        }
        if (that.data.flag === 0) {
            api.showError('评分不能为空')
            return
        }
        let text = that.data.text;
        var data2 = {
            city: that.data.city,
        }

        if(text=='大家一起来巡河啊'){
             text = "#一起去巡河#"+util.formatTimeAll(new Date())+','+that.data.city+'，天气'+wx.getStorageSync("cond_txt")
        }
        wx.showLoading({"title":"提交中，请稍后..."})
        console.log(text);
        let data = {
            intro: text,
            photos: that.data.photos.join(","),
            isexist: that.data.whether,
            account_id: that.data.account_id,
            rp_id: that.data.rpid,
            longitude: that.data.longitude,
            latitude: that.data.latitude,
            address: that.data.address,
            district: that.data.district,
            province: that.data.province,
            city: that.data.city,
            river_worse: that.data.problem_num.join(","),
            river_goods: that.data.select_num.join(","),
            score: that.data.flag,
        }
        let url = app.u.H + app.u.river.ADDMARK
        api.requestUrl(data, url).then(res => {
            api.showSuccess("标记成功")
            if (res.code == 200) {
                wx.hideLoading();
                wx.setStorageSync('fresh', 1)
                setTimeout(function() {
                    wx.switchTab({
                        url: '/pages/newpage/newpage'
                    })
                }, 1000)
            } else {
                wx.hideLoading();
            }

        })
    }
})